package com.ss.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
@Aspect
public class OrderServiceAspect {

    // 切点1：匹配com.ss.service.OrderService.add、delete、find所有方法
    @Pointcut("execution(* com.ss.service.OrderService.add(..)) || execution(* com.ss.service.OrderService.delete(..)) || execution(* com.ss.service.OrderService.find(..))")
    public void allBusinessMethods() {}

    // 切点2：匹配add和delete方法
    @Pointcut("execution(* com.ss.service.OrderService.add(..)) || execution(* com.ss.service.OrderService.delete(..))")
    public void modifyMethods() {}

    // 切点3：匹配OrderService接口的所有方法
    @Pointcut("execution(* com.ss.service.OrderService.*(..))")
    public void allOrderServiceMethods() {}

    // 1. 前置增强：对add, delete, find方法
    @Before("allBusinessMethods()")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }

    // 2. 后置增强：对add, delete方法
    @AfterReturning("modifyMethods()")
    public void afterAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 3. 获取方法返回值并输出
    @AfterReturning(pointcut = "allOrderServiceMethods()", returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        if (result != null) {
            System.out.println(methodName + "方法的返回值: " + result);
        } else {
            System.out.println(methodName + "方法没有返回值");
        }
    }

    // 4. 计算方法执行时间
    @Around("allOrderServiceMethods()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed(); // 执行目标方法
        long endTime = System.currentTimeMillis();
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName + "方法执行时间: " + (endTime - startTime) + "毫秒");
        return result;
    }

    // 5. 权限检查增强：对add, delete方法
    @Before("modifyMethods()")
    public void permissionCheck(JoinPoint joinPoint) throws Throwable {
        Random random = new Random();
        int permission = random.nextInt(2); // 生成0或1的随机数

        String methodName = joinPoint.getSignature().getName();
        if (permission == 0) {
            System.out.println("权限检查通过，可以执行" + methodName + "方法");
        } else {
            System.out.println("没有权限执行" + methodName + "方法，操作被终止");
            // 抛出异常终止方法执行
            throw new RuntimeException("权限不足，无法执行" + methodName + "操作");
        }
    }
}
    